<template>
  <div>
    <input v-model="keyword" placeholder="搜索帖子" @keyup.enter="searchPosts" />
    <button @click="searchPosts">搜索</button>
    <button @click="goToCreatePost">发布帖子</button>
    <ul>
      <li v-for="post in posts" :key="post.id">
        <h3>{{ post.title }}</h3>
        <p>{{ post.content }}</p>
        <button @click="goToEditPost(post.id)">修改</button>
        <button @click="likePost(post.id)">点赞</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const keyword = ref('');
const posts = ref([]);

const fetchPosts = async () => {
  try {
    const response = await axios.get('/api/posts');
    posts.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

const searchPosts = async () => {
  try {
    const response = await axios.get(`/api/posts/search?keyword=${keyword.value}`);
    posts.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

const goToCreatePost = () => {
  router.push('/create-post');
};

const goToEditPost = (postId) => {
  router.push(`/edit-post/${postId}`);
};

const likePost = async (postId) => {
  try {
    await axios.post('/api/likes', {
      userId: 1, // 假设用户 ID 为 1
      postId: postId
    });
    alert('点赞成功');
    fetchPosts();
  } catch (error) {
    console.error(error);
  }
};

fetchPosts();
</script>